<template>
  <MenuPage
    :columns="attackCol"
    :data="attackData"
    :loading="attackLoading"
    :total="toolTotal"
    :size.sync="toolPageSize"
    :page.sync="toolPage"
    @queuryFun="getDataList"
  >
    <template slot="search">
      <Input
        v-model.trim="toolModelInput"
        placeholder="工具名称"
        clearable
        @on-change="searchToolNameBtn"
        style="width: 150px;margin-right: 15px"
      />
      <Button title="重置" @click="refreshTool"><i class="el-icon-refresh-right"/></Button>
    </template>
    <!--实物设备列表-->
    <Modal v-model="toolDeviModal" :mask-closable="false" width="800" title="实物设备">
      <Table :columns="toolCol" :data="toolDeviceList" max-height="650"></Table>
    </Modal>
    <!--虚拟设备列表-->
    <Modal v-model="vmDeviceModal" :mask-closable="false" width="800" title="实物设备">
      <Table :columns="vmDeviceCol" :data="vmDeviceList" max-height="650"></Table>
    </Modal>
    <!--绑定工具-->
    <DrawerPage
      width="800"
      v-model="addDeviceModel"
    >
      <div style="display: flex;justify-content: flex-start;align-items: center">
        <div style="height: 8px;width: 8px;border-radius: 50%;background-color: #333"></div>
        <div style="margin-left: 5px;font-size: 18px;font-weight: 700">攻防工具分配</div>
      </div>
      <div style="display: flex;justify-content: space-between;margin-top: 20px">
        <div style="margin-left: 15px;font-size: 14px;font-weight: bold">
          单位内设计师（{{ this.userTotal }}）
        </div>
        <Input
          v-model.trim="addSearchComMemInput"
          clearable
          placeholder="userName"
          style="width: 200px"
          @on-enter="addSearchComMem"
          @on-clear="clearInput"
        />
      </div>
      <Divider />
      <div>
        <Table :columns="memCol" :data="comMemberList" :height="setUserTableHei"></Table>
      </div>
      <div style="display: flex;justify-content: flex-start;margin-top: 20px">
        <Button style="margin-right: 8px" type="primary" @click="addAssign">分配</Button>
        <Button @click="addDeviceModel = false">取消</Button>
      </div>
    </DrawerPage>
  </MenuPage>
</template>
<script>
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import {
  getAttackData,
  getAllDesigner,
  getAllDesignerUserName,
  distriToolDevice,
  cancelDistriToolDevice
} from '@/api/device.js';
import ToolList from '@/components/attackTool/toolList.vue';
import ToolType from '@/components/attackTool/toolType.vue';
export default {
  components: { ToolList, ToolType },
  data() {
    return {
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      companyId: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      setTableHei: 'auto',
      // 单位内所有设计师
      allDesigner: [],
      // 数据
      attackData: [],
      attackCol: [
        {
          type: 'index',
          width: 60,
          align: 'left',
          fixed: 'left'
        },
        {
          title: '名称',
          key: 'name',
          align: 'left',
          fixed: 'left',
          minWidth: 120
        },
        {
          title: '训练科目',
          key: '',
          align: 'left',
          minWidth: 120,
          render: (h, params) => {
            return h(ToolList, {
              props: {
                row: params.row.subjects
              }
            });
          }
        },
        {
          title: '类型', // tags
          key: '',
          align: 'left',
          minWidth: 120,
          render: (h, params) => {
            return h(ToolType, {
              props: {
                row: params.row.tags
              }
            });
          }
        },
        {
          title: '实物设备', // toolDevices
          key: '',
          align: 'left',
          width: 90,
          render: (h, params) => {
            if (params.row.toolDevices.length > 0) {
              return h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.showToolDeviceData(params.row.toolDevices);
                    }
                  }
                },
                '查看'
              );
            } else {
              return h('div', '-');
            }
          }
        },
        {
          title: '虚拟设备', // toolVms
          key: '',
          align: 'left',
          width: 90,
          render: (h, params) => {
            if (params.row.toolVms.length > 0) {
              return h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.vmDeviceData(params.row.toolVms);
                    }
                  }
                },
                '查看'
              );
            } else {
              return h('div', '-');
            }
          }
        },
        {
          title: '是否分配',
          key: '',
          align: 'left',
          width: 90,
          render: (h, params) => {
            let text = '';
            let color = 'rgb(237, 75, 77)';
            if (params.row.isAssign) {
              text = '是';
              color = 'green';
            } else {
              text = '否';
            }
            return h(
              'div',
              {
                style: {
                  color: color
                }
              },
              text
            );
          }
        },
        {
          title: '使用人员',
          key: 'userName',
          align: 'left',
          width: 100,
          tooltip: true
        },
        {
          title: '人员ID',
          key: 'userId',
          align: 'left',
          width: 120,
          tooltip: true
        },
        {
          title: '用途',
          key: 'purpose',
          align: 'left',
          width: 100,
          tooltip: true
        },
        {
          title: '描述',
          key: 'description',
          align: 'left',
          width: 120,
          tooltip: true
        },
        {
          title: '更新时间',
          key: 'updateTime',
          align: 'left',
          width: 150,
          sortable: true,
          sortType: 'desc',
          tooltip: true
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'left',
          width: 150,
          sortable: true,
          tooltip: true
        },
        {
          title: '操作',
          key: 'action',
          align: 'left',
          width: 150,
          render: (h, params) => {
            let arr = [];
            let getId = params.row.userId ? params.row.userId : '';
            let isFlag = true;
            if (getId === this.USER_ID || this.isRootDesigner) {
              isFlag = false;
            }
            if (params.row.toolDevices.length === 0) {
              return h('div', '--');
            } else if (params.row.isAssign) {
              arr.push(
                h(
                  'a',
                  {
                    attrs: {
                      disabled: isFlag
                    },
                    style: {
                      display: 'flex',
                      'justify-content': 'flex-start',
                      'align-items': 'center',
                      color: isFlag ? '' : '#2f70ff'
                    }
                  },
                  [
                    h(
                      'Poptip',
                      {
                        props: {
                          confirm: true,
                          transfer: true,
                          title: '确定要取消分配吗？'
                        },
                        on: {
                          'on-ok': () => {
                            this.delAssign(params.row);
                          },
                          'on-cancel': () => {}
                        }
                      },
                      [
                        h('img', {
                          attrs: {
                            src: isFlag
                              ? require('../../assets/globalIcon/dis-cancel-ration.png')
                              : require('../../assets/globalIcon/cancel-ration.png')
                          },
                          style: {
                            cursor: 'pointer',
                            'margin-right': '5px',
                            'vertical-align': 'middle',
                            width: '16px',
                            height: '16px',
                            display: 'inline-block'
                          }
                        }),
                        h(
                          'span',
                          {
                            style: {
                              cursor: 'pointer'
                            }
                          },
                          '取消分配'
                        )
                      ]
                    )
                  ]
                )
              );
            } else {
              arr.push(
                h(
                  'a',
                  {
                    attrs: {
                      disabled: isFlag
                    },
                    style: {
                      color: isFlag ? '' : '#2f70ff'
                    }
                  },
                  [
                    h(
                      'div',
                      {
                        on: {
                          click: () => {
                            this.addAssignBtn(params.row);
                          }
                        }
                      },
                      [
                        h('img', {
                          attrs: {
                            src: isFlag
                              ? require('../../assets/globalIcon/dis-ration.png')
                              : require('../../assets/globalIcon/ration.png')
                          },
                          style: {
                            cursor: 'pointer',
                            'margin-right': '5px',
                            'vertical-align': 'middle',
                            width: '16px',
                            height: '16px',
                            display: 'inline-block'
                          }
                        }),
                        h(
                          'span',
                          {
                            style: {
                              cursor: 'pointer'
                            }
                          },
                          '分配'
                        )
                      ]
                    )
                  ]
                )
              );
            }
            return h('div', arr);
          }
        }
      ],
      attackLoading: false,
      toolId: '',
      toolTotal: 0,
      toolPageSize: 12,
      toolPage: 1,
      // selectToolType:'all',
      toolModelInput: '',
      // 实物设备列表
      toolDeviModal: false,
      toolDeviceList: [],
      toolCol: [
        {
          type: 'index',
          width: 70,
          align: 'left'
        },
        {
          title: '实物设备ID',
          key: 'deviceId',
          align: 'left'
        },
        {
          title: '实物设备名称',
          key: 'deviceName',
          align: 'left'
        },
        {
          title: '描述',
          key: 'description',
          align: 'left'
        },
        {
          title: '更新时间',
          key: 'updateTime',
          align: 'left',
          width: 180
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'left',
          width: 180
        }
      ],
      // 虚拟设备列表
      vmDeviceModal: false,
      vmDeviceList: [],
      vmDeviceCol: [
        {
          type: 'index',
          width: 70,
          align: 'left'
        },
        {
          title: '配额名称',
          key: 'flavorName',
          align: 'left'
        },
        {
          title: '镜像名称',
          key: 'imageName',
          align: 'left'
        },
        {
          title: '描述',
          key: 'description',
          align: 'left'
        },
        {
          title: '更新时间',
          key: 'updateTime',
          align: 'left',
          width: 180
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'left',
          width: 180
        }
      ],
      // 绑定工具
      userTotal: 0,
      setUserTableHei: '700',
      addDeviceModel: false,
      submitAddMemLoading: false,
      memCol: [
        {
          title: '请选择',
          width: 80,
          key: 'checkBox',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Checkbox', {
                props: {
                  value: params.row.checkBox
                },
                on: {
                  'on-change': (e) => {
                    this.comMemberList.forEach((items) => {
                      this.$set(items, 'checkBox', false);
                    });
                    this.comMemberList[params.row._index].checkBox = true;
                    this.selectUserId = params.row.id;
                    this.selectUserName = params.row.username;
                  }
                }
              })
            ]);
          }
        },
        {
          title: 'userName',
          key: 'username',
          align: 'center'
        },
        {
          title: 'Nicknameinfo',
          key: 'nickname',
          align: 'center'
        },
        {
          title: 'type',
          key: 'type',
          align: 'center'
        },
        {
          title: 'Role',
          key: 'role',
          align: 'center'
        },
        {
          title: 'Online',
          key: 'online',
          align: 'center'
        },
        {
          title: 'creatorName',
          key: 'creatorName',
          align: 'center'
        },
        {
          title: 'CTime',
          key: 'created',
          align: 'center',
          width: 150
        }
      ],
      comMemberList: [],
      selectUserId: '',
      selectUserName: '',
      addSearchComMemInput: ''
    };
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.companyId = November.companyId;
  },
  mounted() {
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
    this.init();
  },
  methods: {
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.contentHei = this.fullHeight - 80 - 60 + 'px'; // 80是头部高度  60是上下padding
      this.setTableHei = this.fullHeight - 80 - 60 - 52 - 49 - 65;
      this.setUserTableHei = this.fullHeight - 230;
      this.toolPageSize = Math.floor((this.fullHeight - 206) / 55) - 1;
    },
    // 初始化
    init() {
      this.getAllDesigner().then(() => {
        this.getDataList();
      });
    },
    // 单位内成员
    getAllDesigner() {
      return new Promise((resolve, reject) => {
        getAllDesigner()
          .then((res) => {
            if (res.data.code == 1) {
              let items = res.data.data;
              for (let i = 0; i < items.length; i++) {
                this.allDesigner.push(items[i].id);
              }
              resolve(this.allDesigner);
            }
          })
          .catch((err) => {
            console.log(err);
            this.$Message.error('服务器连接失败！');
          });
      });
    },
    // 获取攻防工具列表
    getDataList() {
      let params = {
        companyId: this.companyId,
        page: this.toolPage,
        size: this.toolPageSize
      };
      let toolsrch = {};
      if (this.toolModelInput != '') {
        toolsrch.name = this.toolModelInput;
      }
      this.attackLoading = true;
      getAttackData(params, toolsrch)
        .then((res) => {
          if (res.data.code === 1) {
            let getData = res.data.data;
            let items = getData.list;
            this.toolTotal = getData.total;
            for (let i = 0; i < items.length; i++) {
              let usid = items[i].userId ? items[i].userId : '';
              if (this.allDesigner.indexOf(usid) > -1) {
                items[i].isAssign = true;
              } else {
                items[i].isAssign = false;
              }
            }
            this.attackData = items;
          }
          this.attackLoading = false;
        })
        .catch((err) => {
          this.attackLoading = false;
          console.log(err);
        });
    },
    toolOnChange(val) {
      this.toolPage = val;
      this.getDataList();
    },
    // selectToolTypeChange(val){
    //
    // },
    searchToolNameBtn() {
      this.toolModelInput = this.toolModelInput;
      this.getDataList();
    },
    refreshTool() {
      this.toolPage = 1;
      this.toolModelInput = '';
      this.getDataList();
    },
    // 实物设备展示
    showToolDeviceData(list) {
      this.toolDeviceList = list;
      this.toolDeviModal = true;
    },
    // 虚拟设备展示
    vmDeviceData(list) {
      this.vmDeviceList = list;
      this.vmDeviceModal = true;
    },
    // 取消分配
    delAssign(row) {
      let id = row.id;
      cancelDistriToolDevice(id)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success({
              content: '取消分配成功',
              duration: 3
            });
            this.getDataList();
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.$Message.error('服务器连接失败！');
        });
    },
    // 绑定设备
    addAssignBtn(row) {
      this.toolId = row.id;
      this.selectUserId = '';
      this.selectUserName = '';
      this.addSearchComMemInput = '';
      this.searchDesigner();
      this.addDeviceModel = true;
    },
    // 查询设计师
    searchDesigner() {
      let setParams = '';
      if (this.addSearchComMemInput != '') {
        setParams = `?username=${this.addSearchComMemInput}`;
      }
      this.comMemberList = [];
      getAllDesignerUserName(setParams)
        .then((res) => {
          if (res.data.code == 1) {
            let items = res.data.data;
            this.userTotal = items.length;
            for (let i = 0; i < items.length; i++) {
              items[i].checkBox = false;
              this.comMemberList.push(items[i]);
            }
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.$Message.error('服务器连接失败！');
        });
    },
    addAssign() {
      this.submitAddMemLoading = true;
      let params = {
        id: this.toolId,
        data: {
          userId: this.selectUserId,
          userName: this.selectUserName
        }
      };
      distriToolDevice(params)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success({
              content: '分配成功',
              duration: 3
            });
            this.toolId = '';
            this.addDeviceModel = false;
            this.getDataList();
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
          this.submitAddMemLoading = false;
        })
        .catch((err) => {
          console.log(err);
          this.submitAddMemLoading = false;
          this.$Message.error('服务器连接失败！');
        });
    },
    // username搜索
    addSearchComMem() {
      this.searchDesigner();
    },
    // 清空input触发
    clearInput() {
      this.addSearchComMemInput = '';
      //this.searchDesigner()
    },
    // 关闭抽屉
    closeDistribution() {
      this.addDeviceModel = false;
    }
  }
};
</script>
<style scoped>
.page-wrap {
  padding: 30px;
}
.page-content {
  background-color: #fff;
  border-radius: 10px;
}
.img-header {
  display: flex;
  justify-content: space-between;
  padding: 20px 30px 0 30px;
}
.table-wrap {
  padding: 0 30px;
}
.deviceDrawer {
  position: relative;
}
</style>
<style>
.table-wrap .ivu-table-overflowX {
  overflow-x: auto;
}
.table-wrap .ivu-table-overflowX::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 6px;
}
.table-wrap .ivu-table-overflowX::-webkit-scrollbar-thumb {
  /*滚动条里面小方块样式*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(209, 209, 209, 0.6);
}
.table-wrap .ivu-table-overflowX::-webkit-scrollbar-track {
  /*滚动条里面轨道样式*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  background: rgba(179, 179, 179, 0.1);
}
.deviceDrawer .ivu-drawer-body {
  overflow: inherit;
}
.attack-wrap .ivu-table-fixed {
  height: 100%;
}
</style>
